import myReq from '../../request'
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    reg:true,
    hasuserInfo: true,
    data: {
      swiperInfos: "",
      img: "",
      goodID: "",
      price: "",
      createTime: "",
      updateTime: "",
      isNew: "",
      infoId: "",
      brand: "",
      weight: "",
      origin: "",
      info: "",
      colour: "",
      edition: "",
      state: 1,
      shopCount: 0,
      showCount: 0,
      loading: true
    },
    tag: {
      addrTag: false,
      carTag: false,
      payTag: false,
      shadowTag: true,
    },
    isgocart: false,
    nowPop: "",
    animationData: {},
    shadowAnimation: {},
    token: "",
    sizeState: true,
    parameterTitle: '',
    animationSize: {},
  },
  closeadd() {
    let obj = this.data.tag
    obj.addrTag = "";
    this.closeShadow()
    this.setData({
      tag: obj
    })
  },

  // 接口
  getOpenid: function () {
    let that = this;
    wx.login({
      success: function (res) {
        wx.request({
          method: "POST",
          url: "http://api_dev.wanxikeji.cn/api/codeExchangeOpenid",
          data: {
            code: res.code
          },
          success: function (response) {
            console.log(response)
            var openid = response.data.data.openid;
            // openid存缓存
            wx.setStorageSync('openid', openid);

            // token存缓存

            // 个人信息存缓存
            if (response.data.data.info) {
              var token = response.data.data.info.token;
              console.log(token)
              wx.setStorageSync('token', token);
              wx.setStorageSync('person_info', response.data.data.info);
              that.setData({
                icon: response.data.data.info.icon,
                nick_name: response.data.data.info.nick_name,
                hasUserInfo: true
              })
            }
            that.setData({
              openid: openid,
            })
          },
        })
      }
    })
  },
  closedet() {
    this.setData({
      sizeState: true
    })
    var animation = wx.createAnimation({
      duration: 300
    })

    animation.height(0).opacity(1).step()

    this.setData({
      animationSize: animation.export()
    })
  },
  // 关闭弹窗
  myevent(e) {

    if (e.detail) {
      var count = ++this.data.data.showCount

      this.setData({
        ['data.showCount']: count
      })

    }

    let tag = this.data.tag
    tag.shadowTag = !tag.shadowTag
    this.setData({
      tag,
      nowPop: ""
    })
   
  },
  // 打开购物车弹框
  openShopCar() {
    let tag = this.data.tag
    tag.carTag = true
    this.openShadow()
    this.setData({
      tag,
      nowPop: "carTag"
    })
    
  },
  // 加入购物车
  joinShopCar() {

    var that = this
  

    this.setData({
      ['data.state']: 1
    })

    wx.getStorage({
      key: 'token',
      success() {
        that.openShopCar()
      }
    })
  },
  // 立即购买
  shopNow() {

    var that = this

    this.setData({
      ['data.state']: 2
    })

    wx.getStorage({
      key: 'token',
      success() {
        let tag = that.data.tag
        tag.payTag = true
        that.openShadow()
        that.setData({
          tag,
          nowPop: "payTag"
        })
      }
    })
  },
  // 前往购物车
  toShopCar() {
    if (wx.getStorageSync('token')) {
 
      wx.navigateTo({
        url: '../shopping_Cart/shopping_Cart',
      })
    }
  },
  // 打开遮罩层
  openShadow() {
    let tag = this.data.tag
    tag.shadowTag = false
    this.setData({
      tag
    })
  },


  // 关闭遮罩层
  closeShadow() {
    let tag = this.data.tag
    tag.shadowTag = true
    this.setData({
      tag
    })
  },

  // 关闭弹出层
  closePop() {
    if (this.data.nowPop === "addrTag") {
      let animation = wx.createAnimation({
        duration: 300
      })
      animation.height(0).opacity(0).step()
      this.setData({
        animationData: animation.export()
      })
    } else {
      this.selectComponent("#config").closePop()
    }
    this.closeShadow()
    setTimeout(() => {
      let nowPop = this.data.nowPop
      let tag = this.data.tag
      tag[nowPop] = false
      this.setData({
        tag,
        nowPop: ""
      })
    }, 300)
  },
  // 处理地址数据
  delAddr(addrs) {
    let tmp = []
    // 循环地址列表数据
    addrs.forEach(item => {
      let {
        procince,
        city,
        area,
        detailed,
        default: tacitly,
        name,
      } = item;
      // 设置是否为默认样式
      let isDefault = tacitly === 1 ? true : false
      // 拼接地址
      let addr = procince + city + area + detailed
      tmp.push({
        addr,
        isDefault,
        name
      })
    })
    // 循环处理过后的数据    
    tmp.forEach((item, index) => {
      // 如果是默认地址
      if (item.isDefault) {
        // 删除这条数据
        let firstAddr = tmp.splice(index, 1)[0]
        // 并将其推入数组第一个
        tmp.unshift(firstAddr)
        // 设置默认展示的地址
        this.setData({
          choosedAddress: item
        })
      }
    })
    return tmp
  },

  // 去添加地址
  toAddAddr() {
    const self = this
    wx.navigateTo({
      url: '../../pages/addAddress/addAddress',
      events: {
        addrSuccess(res) {
          const addrList = res.data.data
          const deledAddrs = self.delAddr(addrList)
          self.setData({
            addrList,
            deledAddrs
          })

        }
      }
    })
  },
  // 打开选择地址列表
  openAddr() {
    if (!wx.getStorageSync('token')) {
      return
    }
    this.getaddress()
    let tag = this.data.tag
    tag.addrTag = true
    this.setData({
      tag,
      nowPop: "addrTag"
    })
    this.openShadow()

    let animation = wx.createAnimation({
      duration: 300
    })
    animation.height(this.data.boxH).opacity(1).step()
    this.setData({
      animationData: animation.export()
    })
  },
  // 关闭地址选择列表
  closeAddr() {
    let animation = wx.createAnimation({
      duration: 300
    })
    animation.height(0).opacity(0).step()
    this.setData({
      animationData: animation.export()
    })
    setTimeout(() => {
      let tag = this.data.tag
      tag.addrTag = false
      this.setData({
        tag,
        nowPop: ""
      })
      this.closeShadow()
    }, 300)


  },
  // 选择地址
  chooseAddr(e) {
    const {
      addrIndex
    } = e.currentTarget.dataset
    let data = this.data.deledAddrs
    let firstAddr = data.splice(addrIndex, 1)[0]
    
    wx.setStorageSync('detaddress', firstAddr)
    data.unshift(firstAddr)
    this.setData({
      deledAddrs: data,
      choosedAddress: firstAddr,
      addrTag: false
    })
    this.closeAddr()
  },
  getaddress() {
    let self = this
    // 获取token
    let getToken = new Promise((resolve, reject) => {
      wx.getStorage({
        key: 'token',
        success(res) {
          resolve(res.data)
        }
      })
    })

    getToken.then(
      res => {
        // 获取地址数据
        
        myReq({
          url: 'http://api_dev.wanxikeji.cn/api/userAddressList',
          method: "POST",
          data: {
            token: res
          },
        }).then(
          res => {
           
            const addrList = res.data.data
            const deledAddrs = self.delAddr(addrList)
            self.setData({
              addrList,
              deledAddrs
            })
            
          },
          err => {
          
            const addrList = []
            const deledAddrs = []
            self.setData({
              addrList,
              deledAddrs
            })
          }
        )
      },
      err => {
        wx.redirectTo({
          url: '../myinfo/myinfo'
        })
      }
    )
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function ({
    good_id
  }) {
    if (wx.getStorageSync('detaddress') == "") {
      this.setData({
        choosedAddress: wx.getStorageSync('detaddress')
      })
    }
    const self = this
    let token=false
    //获取token
    let getToken = new Promise((resolve, reject) => {
      wx.getStorage({
        key: 'token',
        success(res) {
          resolve(res.data)
        }
      })
    }).then(re => {
        token = re
      },
      rej => {
       
      }
    )

    
    if(token!=false){
      if (token == '') {

        wx.getStorage({
          key: 'openid',
          success(res) {
            
            if (res.data){
              wx.request({
                url: 'http://api_dev.wanxikeji.cn/api/refreshToken',
                method: "POST",
                data: {
                  openid: res.data
                },
                success(response) {
                  console.log(response)
                  if (response.data.code === 2010) {
                    rej({
                      "code": 2010,
                      "data": [],
                      "msg": "用户已被禁用"
                    })
                    return
                  }
                  wx.setStorage({
                    data: response.data.data.token,
                    key: 'token',
                  })
                  self.setData({
                    token: response.data.data.token,
                  })
  
                  // 获取购物车商品总数
                  wx.getStorage({
                    key: 'token',
                    success(res) {
                      
                      wx.request({
                        url: 'http://api_dev.wanxikeji.cn/api/shoppingCarList',
                        data: {
                          token: res.data
                        },
                        header: {
                          'content-type': 'application/json,charset=utf8' // 默认值
                        },
                        method: 'POST',
                        success(re) {
                          
                          if (re.data.data.data.length > 9) {
                            self.data.data.showCount = '9+'
                          } else {
                            self.data.data.showCount = re.data.data.data.length
                          }
                         
  
                          self.setData({
                            ['data.showCount']: self.data.data.showCount,
                            ['data.shopCount']: re.data.data.data.length
                          })
                        }
                      })
                    }
                  })
  
  
                  // 获取商品详情数据 
                  wx.request({
                    url: 'http://api_dev.wanxikeji.cn/api/goodInfo', //仅为示例，并非真实的接口地址
                    data: {
                      good_id,
                    },
                    header: {
                      'content-type': 'application/json,charset=utf8' // 默认值
                    },
                    method: "POST",
                    success(res) {
                      // 轮播图信息
                   
                      let swiperInfos
                      let {
                        good_id: goodID, // 商品ID
                        good_name: goodName,
                        price,
                        create_time: createTime,
                        update_time: updateTime,
                        img,
                        is_new: isNew
                      } = res.data.data
                      // 如果 info 不为空
                      if (res.data.data.info.length) {
                        // 如果 info 下面的图集中 imgs 不为空
                        var {
                          info_id: infoId,
                          brand,
                          weight,
                          origin,
                          info,
                          colour,
                          edition
                        } = res.data.data.info[0]
                        colour = JSON.parse(colour)
                        edition = JSON.parse(edition)
                        info = JSON.parse(info)
                        if (res.data.data.info[0].imgs) {
                          // 轮播图就使用图集
                          swiperInfos = JSON.parse(res.data.data.info[0].imgs)
                        } else {
                          // 如果不存在，就是用data下面的封面图
                          swiperInfos = [res.data.data.img]
                        }
                      } else {
                        wx.showToast({
                          title: '该商品暂无库存',
                          icon: 'none'
                        })
                        setTimeout(function () {
                          wx.navigateBack({
  
                          })
                        }, 3000)
                        // 如果不存在，就是用data下面的封面图
                        swiperInfos = [res.data.data.img]
                      };
  
                      var str = ''
  
                      try {
                        Object.keys(colour).forEach(item => {
                          str += item + ' '
                        })
                      } catch (error) {}
  
  
                      self.setData({
                        data: {
                          swiperInfos,
                          img,
                          goodID,
                          goodName,
                          price,
                          createTime,
                          updateTime,
                          isNew,
                          infoId,
                          brand,
                          weight,
                          origin,
                          info,
                          colour,
                          edition
                        },
                        parameterTitle: str,
                        loading: false
                      })
                    }
                  })
  
                  wx.getSystemInfo({
                    success: res => {
                      //导航高度
                      let navH = res.statusBarHeight + 46
                      let boxH = res.windowHeight - navH
                      self.setData({
                        navH,
                        boxH
                      });
                    },
                    fail(err) {
                    
                    }
                  })
                }
              })
            }
          }
        })
      }
      else{
         // 获取购物车商品总数
         wx.getStorage({
          key: 'token',
          success(res) {
            wx.request({
              url: 'http://api_dev.wanxikeji.cn/api/shoppingCarList',
              data: {
                token: res.data
              },
              header: {
                'content-type': 'application/json,charset=utf8' // 默认值
              },
              method: 'POST',
              success(re) {
                
                if (re.data.data.data.length > 9) {
                  self.data.data.showCount = '9+'
                } else {
                  self.data.data.showCount = re.data.data.data.length
                }
               
  
                self.setData({
                  ['data.showCount']: self.data.data.showCount,
                  ['data.shopCount']: re.data.data.data.length
                })
              }
            })
          }
        })
  
  
        // 获取商品详情数据 
        wx.request({
          url: 'http://api_dev.wanxikeji.cn/api/goodInfo', //仅为示例，并非真实的接口地址
          data: {
            good_id,
          },
          header: {
            'content-type': 'application/json,charset=utf8' // 默认值
          },
          method: "POST",
          success(res) {
            // 轮播图信息
          
            let swiperInfos
            let {
              good_id: goodID, // 商品ID
              good_name: goodName,
              price,
              create_time: createTime,
              update_time: updateTime,
              img,
              is_new: isNew
            } = res.data.data
            // 如果 info 不为空
            if (res.data.data.info.length) {
              // 如果 info 下面的图集中 imgs 不为空
              var {
                info_id: infoId,
                brand,
                weight,
                origin,
                info,
                colour,
                edition
              } = res.data.data.info[0]
              colour = JSON.parse(colour)
              edition = JSON.parse(edition)
              info = JSON.parse(info)
              if (res.data.data.info[0].imgs) {
                // 轮播图就使用图集
                swiperInfos = JSON.parse(res.data.data.info[0].imgs)
              } else {
                // 如果不存在，就是用data下面的封面图
                swiperInfos = [res.data.data.img]
              }
            } else {
              wx.showToast({
                title: '该商品暂无库存',
                icon: 'none'
              })
              setTimeout(function () {
                wx.navigateBack({
  
                })
              }, 3000)
              // 如果不存在，就是用data下面的封面图
              swiperInfos = [res.data.data.img]
            };
  
            var str = ''
  
            try {
              Object.keys(colour).forEach(item => {
                str += item + ' '
              })
            } catch (error) {}
  
  
            self.setData({
              data: {
                swiperInfos,
                img,
                goodID,
                goodName,
                price,
                createTime,
                updateTime,
                isNew,
                infoId,
                brand,
                weight,
                origin,
                info,
                colour,
                edition
              },
              parameterTitle: str,
              loading: false
            })
          }
        })
  
        wx.getSystemInfo({
          success: res => {
            //导航高度
            let navH = res.statusBarHeight + 46
            let boxH = res.windowHeight - navH
            self.setData({
              navH,
              boxH
            });
          },
          fail(err) {
         
          }
        })
      }
    }
    else{
      // 获取商品详情数据 
    wx.request({
      url: 'http://api_dev.wanxikeji.cn/api/goodInfo', //仅为示例，并非真实的接口地址
      data: {
        good_id,
      },
      header: {
        'content-type': 'application/json,charset=utf8' // 默认值
      },
      method: "POST",
      success(res) {
        // 轮播图信息
      
        let swiperInfos
        let {
          good_id: goodID, // 商品ID
          good_name: goodName,
          price,
          create_time: createTime,
          update_time: updateTime,
          img,
          is_new: isNew
        } = res.data.data
        // 如果 info 不为空
        if (res.data.data.info.length) {
          // 如果 info 下面的图集中 imgs 不为空
          var {
            info_id: infoId,
            brand,
            weight,
            origin,
            info,
            colour,
            edition
          } = res.data.data.info[0]
          colour = JSON.parse(colour)
          edition = JSON.parse(edition)
          info = JSON.parse(info)
          if (res.data.data.info[0].imgs) {
            // 轮播图就使用图集
            swiperInfos = JSON.parse(res.data.data.info[0].imgs)
          } else {
            // 如果不存在，就是用data下面的封面图
            swiperInfos = [res.data.data.img]
          }
        } else {
          wx.showToast({
            title: '该商品暂无库存',
            icon: 'none'
          })
          setTimeout(function () {
            wx.navigateBack({

            })
          }, 3000)
          // 如果不存在，就是用data下面的封面图
          swiperInfos = [res.data.data.img]
        };

        var str = ''

        try {
          Object.keys(colour).forEach(item => {
            str += item + ' '
          })
        } catch (error) {}

        self.setData({
          data: {
            swiperInfos,
            img,
            goodID,
            goodName,
            price,
            createTime,
            updateTime,
            isNew,
            infoId,
            brand,
            weight,
            origin,
            info,
            colour,
            edition
          },
          parameterTitle: str,
          loading: false
        })
      }
    })
    
      self.setData({
        ['data.showCount']: 0,
        ['data.shopCount']: 0
      })
    }
      
  },
  onShow: function () {

    let self = this
    // 获取购物车商品总数
    wx.getStorage({
      key: 'token',
      success(res) {
       
        if (res.data == '') {
          wx.getStorage({
            key: 'openid',
            success(res){
              if(res.data){
                wx.request({
                  url: 'http://api_dev.wanxikeji.cn/api/refreshToken',
              method: "POST",
              data: {
                openid: res.data
              },
              success(response) {
                if (response.data.code === 2010) {
                  rej({
                    "code": 2010,
                    "data": [],
                    "msg": "用户已被禁用"
                  })
                  return
                }
                wx.setStorage({
                  data: response.data.data.token,
                  key: 'token',
                })
                self.setData({
                  token: response.data.data.token,
                })
                wx.request({

                  url: 'http://api_dev.wanxikeji.cn/api/shoppingCarList',
                  data: {
                    token: res.data
                  },
                  header: {
                    'content-type': 'application/json,charset=utf8' // 默认值
                  },
                  method: 'POST',
                  success(re) {
                   
                    if (re.data.data.data.length > 9) {
                      self.data.data.showCount = '9+'
                    } else {
                      self.data.data.showCount = re.data.data.data.length
                    }
                    
      
                    self.setData({
                      ['data.showCount']: self.data.data.showCount,
                      ['data.shopCount']: re.data.data.data.length
                    })
                  }
                })
              
                }
                })
              }
            }
          })
        } else {
          
          wx.request({

            url: 'http://api_dev.wanxikeji.cn/api/shoppingCarList',
            data: {
              token: res.data
            },
            header: {
              'content-type': 'application/json,charset=utf8' // 默认值
            },
            method: 'POST',
            success(re) {
              try {
                if (re.data.data.data.length > 9) {
                  self.data.data.showCount = '9+'
                } else {
                  self.data.data.showCount = re.data.data.data.length
                }
                
  
                self.setData({
                  ['data.showCount']: self.data.data.showCount,
                  ['data.shopCount']: re.data.data.data.length
                })
              } catch (error) {
                
              }
              
            }
          })
        }

      }
    })
  
    
  },

  getUserInfo(val) {
    
    var that = this
   
    if (this.data.token == '') {
      wx.login({
        success(res) {

          wx.request({
            url: 'http://api_dev.wanxikeji.cn/api/codeExchangeOpenid',
            method: 'POST',
            data: {
              code: res.code
            },
            header: {
              "content-type": "application/json;charset=UTF-8"
            },
            success(res) {
              
              if (res.data.data.info) {

                var obj = {}
                obj.icon = val.detail.userInfo.avatarUrl
                obj.nick_name = val.detail.userInfo.nickName
                obj.openid = res.data.data.openid

                wx.setStorage({
                  data: res.data.data.info.token,
                  key: 'token',
                })
                wx.setStorage({
                  data: res.data.data.info,
                  key: 'person_info',
                })

                that.setData({
                  token: res.data.data.info.token
                })
              } else {
                var obj = {}
                obj.icon = val.detail.userInfo.avatarUrl
                obj.nick_name = val.detail.userInfo.nickName
                obj.openid = res.data.data.openid

                wx.request({
                  url: 'http://api_dev.wanxikeji.cn/api/register',
                  method: 'POST',
                  header: {
                    "content-type": "application/json;charset=UTF-8"
                  },
                  data: obj,
                  success(re) {
                    

                    if (re.data.msg == '用户已存在') {
                      wx.request({
                        url: 'http://api_dev.wanxikeji.cn/api/refreshToken',
                        method: 'POST',
                        data: {
                          openid: res.data.data.openid
                        },
                        success(e) {

                          that.setData({
                            token: e.data.data.token
                          })
                        }
                      })
                    } else {
                      wx.setStorage({
                        data: re.data.data.token,
                        key: 'token',
                      })
                      
                      wx.setStorage({
                        data: res.data.data,
                        key: 'person_info',
                      })

                      that.setData({
                        reg:false,
                        token: re.data.data.token
                      })
                      wx.setStorage({
                        data: that.data.reg,
                        key: 'reg',
                      })
                    }
                  }
                })
              }
            }
          })
        }
      })

    } else {

    }
  },

  closeSize() {
    this.setData({
      sizeState: true
    })

    var animation = wx.createAnimation({
      duration: 300
    })

    animation.height(0).opacity(0).step()

    this.setData({
      animationSize: animation.export()
    })
  },

  showSize() {
    this.setData({
      sizeState: false
    })

    var animation = wx.createAnimation({
      duration: 300
    })

    animation.height(380).opacity(1).step()

    this.setData({
      animationSize: animation.export()
    })
  },
})